package org.feng.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.feng.entity.Dept;
import org.feng.entity.User;
import org.feng.mapper.UserMapper;
import org.feng.service.DeptService;
import org.feng.service.UserService;
import org.feng.utils.condition.Condition;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author feng
 * @since 2021-08-27
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    private DeptService deptService;

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectOne(Wrappers.<User>query().eq("username", username));
    }

    @Override
    public IPage<User> deptUser(User user, Long deptId) {
        List<Long> list = new ArrayList<>();
        list = findDeptId(list, deptId);
        list.add(deptId);
        return userMapper.selectPage(Condition.getPage(), Condition.getQueryWrapper(user).in("dept_id", list));
    }

    private List<Long> findDeptId(List<Long> list, Long deptId) {
        List<Dept> deptList = deptService.list(Wrappers.<Dept>lambdaQuery().eq(Dept::getParentId, deptId));
        list = deptList.stream().map(Dept::getId).collect(Collectors.toList());
        for (Dept dept : deptList) {
            list.addAll(findDeptId(list, dept.getId()));
        }
        return list;
    }
}
